package landyer.study.charsetdetect;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * User: landy
 * Date: 15/3/17
 * Time: 下午4:10
 */
public class ListAllBom {

    public static final FileFilter JAVA_FILTER = new FileFilter() {
        @Override
        public boolean accept(File file) {
            return file.isDirectory() || file.getName().toLowerCase().endsWith(".java");
        }
    };

    public static void main(String[] args) throws IOException {
        String dir = "/Volumes/apple/xiayu/codes/GodServerCharset";
        File file = new File(dir);
        System.out.println(file.getAbsolutePath());
        List<File> files = new LinkedList<File>();
        collectFiles(file, files);

        System.out.println("file number:" + files.size());
        int flag = 0;
        for (File one : files) {
            byte[] utf8Bom = IOUtils.toByteArray(new FileInputStream(one));
            if (-17 == utf8Bom[0] && -69 == utf8Bom[1] && -65 == utf8Bom[2]) {
                flag++;
                byte[] newContent = Arrays.copyOfRange(utf8Bom, 3, utf8Bom.length);
                FileUtils.writeByteArrayToFile(one, newContent, false);
            }
        }
        System.out.println("flag :" + flag);
    }

    private static void collectFiles(File file, List<File> files) {
        if (file.isDirectory()) {
            for (File one : file.listFiles(JAVA_FILTER)) {
                collectFiles(one, files);
            }
        } else {
            files.add(file);
        }
    }
}
